package org.compiere.process;

import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Properties;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.model.MAttachment;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MClient;
import org.compiere.model.MMailText;
import org.compiere.model.MUser;
import org.compiere.model.X_CMS_Contract;
import org.compiere.model.X_C_BPartner;
import org.compiere.model.X_R_MailText;
import org.compiere.model.X_cms_GWStype;
import org.compiere.model.X_cms_agreement;
import org.compiere.model.X_cms_agreement_line;
import org.compiere.model.X_cms_pattern;
import org.compiere.util.DB;
import org.compiere.util.EMail;
import org.compiere.util.Env;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.utils.AnalogConvertor;

import extend.org.compiere.hrm.SearchReplace;
import extend.org.compiere.utils.Util;

public class CMS_PatternFilling extends SvrProcess {

//	private int p_AD_Client_ID;
//	private int p_AD_Org_ID;
//	private int p_AD_User_ID;
	
	/** Current context					*/
	private Properties m_ctx;
	/**	 */
	private ProcessInfo pi;
	/** */
	private String contractFileGoods = "";
	private String contractFileService = "";
	/** */
	private String localFilePath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator");
	
	private X_cms_pattern pattern;
	
	@Override
	protected void prepare() {
//		p_AD_Client_ID = Env.getAD_Client_ID(getCtx());
//		p_AD_Org_ID = Env.getAD_Org_ID(getCtx());
//	 	p_AD_User_ID = Env.getAD_User_ID(getCtx());
	 	
	 	log.info("");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		
		pattern = new X_cms_pattern(getCtx(), getRecord_ID(), get_TrxName());
		
		contractFileGoods = "ContractGoods_Pattern";
		contractFileService = "ContractGoods_PatternS";
		
	}

	@Override
	protected String doIt() throws Exception {
		
		X_CMS_Contract contract = new X_CMS_Contract(getCtx(), pattern.getCMS_Contract_ID(), get_TrxName());
		contract.setContractSummary(pattern.getSummary());
		contract.setamountwithouttax(pattern.getamountwithouttax());
		
		String sql = "SELECT cms_statusestype_id from cms_statusestype where lower(name) like '%проект%'";
		int cms_status_id = DB.getSQLValue(get_TrxName(), sql);
		
		if(cms_status_id == -1)
			throw new Exception("Невозможно перевести статус договора");
		
		contract.setcms_statusestype_ID(cms_status_id);
		
		if(!contract.save())
			throw new Exception("Данные введены не верно");
		
		if(!this.GetDocument()) {
			throw new Exception("Не удалось создать договор");
		}
		
		//pattern.setProcessed(true);
		pattern.setProcessing(true);
		
		if(!pattern.save())
			throw new Exception("Не удалось завершить процесс");
		
		return null;
	}
	
	private enum GWS {Goods, Work, Service};
	
	private boolean GetDocument() throws Exception {
		
		String replacement = "          ";
		
		X_CMS_Contract contract = new X_CMS_Contract(getCtx(), pattern.getCMS_Contract_ID(), get_TrxName());
		
		String contractFile = "";
		
		GWS gws = null;
		
		if(contract.getcms_GWStype_ID() == X_cms_GWStype.Goods)
		{
			contractFile = contractFileGoods;
			gws = GWS.Goods;
		}
		if(contract.getcms_GWStype_ID() == X_cms_GWStype.Service)
		{
			contractFile = contractFileService;
			gws = GWS.Service;
		}
		
		if(gws == null)
			throw new Exception("Укажите тип ТРУ");
		//
		MAttachmentEntry entry = Util.getAttachment(pi, m_ctx, contractFile);
				
		if(entry == null)
			throw new AdempiereException(Msg.translate(m_ctx, "NotFoundTemplate")+" "+contractFile);
		
		File inputFile = Util.getAttachmentEntryFile(entry);
		// We define a path to generate
		String fileExtension = entry.getName().substring(entry.getName().lastIndexOf("."),entry.getName().length());
		StringBuffer fullPath = new StringBuffer(localFilePath); 
		fullPath.append(contractFile).append(fileExtension); 
		
		HashMap<String, String> searchTerms = new HashMap<String, String>();	
		HashMap<String, String> searchTerms2 = new HashMap<String, String>();
		
		if(pattern.getCustomer() != null)
			searchTerms.put("Customer", pattern.getCustomer());
		else
			searchTerms.put("Customer", replacement);
		
		if(pattern.getCustomerkaz() != null)
			searchTerms2.put("test2", pattern.getCustomerkaz());
		else
			searchTerms2.put("test2", replacement);
				
		if(pattern.getbasis() != null)
			searchTerms.put("basis", pattern.getbasis());
		else
			searchTerms.put("basis", replacement);
		
		if(pattern.getbasiskaz() != null)
			searchTerms2.put("test1", pattern.getbasiskaz());
		else
			searchTerms2.put("test1", replacement);
		
		X_C_BPartner bpartner = new X_C_BPartner(getCtx(), pattern.getC_BPartner_ID(), get_TrxName());		
		
		if(bpartner.getName() != null)
			searchTerms.put("Bpartner", bpartner.getName());
		else
			searchTerms.put("Bpartner", replacement);
		
		if(pattern.getC_BPartnerKaz() != null)
			searchTerms2.put("test3", pattern.getC_BPartnerKaz());
		else
			searchTerms2.put("test3", replacement);
		
		if(pattern.getResponsibleFace() != null)
		{
			if(gws == GWS.Goods)
				searchTerms.put("Director", pattern.getResponsibleFace());
			if(gws == GWS.Service)
				searchTerms.put("Director", pattern.getResponsibleFace());
		}
		else
			searchTerms.put("Director", replacement);

		if(pattern.getResponsibleFacekaz() != null)
		{
			if(gws == GWS.Goods)
				searchTerms2.put("test4", pattern.getResponsibleFacekaz());
			if(gws == GWS.Service)
				searchTerms2.put("test4", pattern.getResponsibleFacekaz());
		}
		else
			searchTerms2.put("test4", replacement);
		
		if(pattern.getbasis2() != null)
			searchTerms.put("osnovanie", pattern.getbasis2());
		else
			searchTerms.put("osnovanie", replacement);
		
		if(pattern.getbasis2kaz() != null)
			searchTerms2.put("test6", pattern.getbasis2kaz());
		else
			searchTerms2.put("test6", replacement);
		
		String date = "";
		String datekaz = "";
		String monthName = "";
		String monthNamekaz = "";

		if(pattern.getDateFrom() != null)
		{
			 date = pattern.getDateFrom().toString();		
			 date = date.substring(8,10) + "." + date.substring(5,7) + "." + date.substring(0,4);
		}
		if(pattern.getDateFromkaz() != null)
		{
			datekaz = pattern.getDateFromkaz().toString();
			datekaz = datekaz.substring(8,10) + "." + datekaz.substring(5,7) + "." + datekaz.substring(0,4);
		}
		else
			datekaz = date;
		
		if(date.length() > 9)
			monthName = "«" + date.substring(0,2) + "» " + Util.getMonthName(pattern.getDateFrom(), Language.AD_Language_en_US, true) + " " + date.substring(6,10) + "г.";
		if(datekaz.length() > 9)
			monthNamekaz = "«" + date.substring(0,2) + "» " + Util.getMonthName(pattern.getDateFrom(), Language.AD_Language_kz_KZ, true) + " " + date.substring(6,10) + "ж.";
		
		if(pattern.getNo() != null)
			searchTerms.put("Test", "№ " + pattern.getNo());
		else
			searchTerms.put("Test", replacement);
		
		if(pattern.getNokaz() != null)
			searchTerms2.put("test7", "№ " + pattern.getNokaz());
		else
			searchTerms2.put("test7", replacement);
		
		if(pattern.getDateFrom() != null)
			searchTerms.put("DateFrom", monthName);
		else
			searchTerms.put("DateFrom", replacement);
		
		if(pattern.getDateFromkaz() != null)
			searchTerms2.put("test5", monthNamekaz);
		else
			searchTerms2.put("test5", replacement);		
		
		if(pattern.getDeliveryPattern() != null)
			searchTerms.put("DeliveryPattern", pattern.getDeliveryPattern());
		else
			searchTerms.put("DeliveryPattern", replacement);
		
		if(pattern.getDeliveryPatternkaz() != null)
			searchTerms2.put("мундеттер", pattern.getDeliveryPatternkaz());
		else
			searchTerms2.put("мундеттер", replacement);
				
		String sql = "SELECT hrm_sumwords(" + pattern.getSummary().toString() + "), hrm_sumwords(" + pattern.getamountwithouttax().toString() + ")";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		pstmt = DB.prepareStatement(sql, get_TrxName());
		rs = pstmt.executeQuery();
		
		String summ = "";
		String summ2 = "";
		try{
			if(rs.next()) {	
				summ = rs.getString(1);
				summ2 = rs.getString(2);
			}
		}
		catch (Exception e){}
		finally{
			pstmt = null;
			rs = null;
		}
		
		if(pattern.getSummary() != null)
			searchTerms.put("Summary", pattern.getSummary().doubleValue() + " (" + summ + ")");
		else 
			searchTerms.put("Summary", replacement);
		
		if(pattern.getSummary() != null)
			searchTerms2.put("слово1", String.valueOf(pattern.getSummary().doubleValue()) + " (" + AnalogConvertor.convertToString(String.valueOf(pattern.getSummary().doubleValue())) + ")");
		else
			searchTerms2.put("слово1", replacement);
		
		if(pattern.getamountwithouttax() != null)
			searchTerms.put("amountwithouttax", pattern.getamountwithouttax().doubleValue() + " (" + summ2 + ")");
		else
			searchTerms.put("amountwithouttax", replacement);
		
		if(pattern.getamountwithouttax() != null)
			searchTerms2.put("слово2", pattern.getamountwithouttax().doubleValue() + " (" + AnalogConvertor.convertToString(String.valueOf(pattern.getamountwithouttax().doubleValue())) + ")");
		else
			searchTerms2.put("слово2", replacement);

		
		X_C_BPartner ZerdeBP = new X_C_BPartner(getCtx(), pattern.getZerdeBP(), get_TrxName());		
		
		if(ZerdeBP.getName() != null)
			searchTerms.put("ZerdeBP", ZerdeBP.getName());
		else
			searchTerms.put("ZerdeBP", replacement);
		
		if(ZerdeBP.getName() != null)
			searchTerms2.put("ОрынбасарДДДД", ZerdeBP.getName());
		else
			searchTerms2.put("ОрынбасарДДДД", replacement);
		
		if(pattern.getProducerName() != null)
			searchTerms.put("ProducerName", pattern.getProducerName());		
		else
			searchTerms.put("ProducerName", replacement);
		
		if(pattern.getProducerNamekaz() != null)
			searchTerms2.put("ОрынбасарАААА", pattern.getProducerNamekaz());		
		else
			searchTerms2.put("ОрынбасарАААА", replacement);
		
		SearchReplace searchReplace = new SearchReplace();				
		
		searchReplace.searchAndReplace(inputFile, fullPath.toString(), searchTerms);
		searchReplace.searchAndReplace(inputFile, fullPath.toString(), searchTerms2);
		
		String title = "Договор";
		String msg = "Договор";
		
		if(gws == GWS.Goods)
		{
			title = "Договор о закупке товаров";
			msg = "Договор о закупке товаров";
		}
		if(gws == GWS.Service)
		{
			title = "Договор о закупке услуг";
			msg = "Договор о закупке услуг";
		}		
		
		sql = "SELECT l.cms_agreement_line_ID FROM adempiere.cms_agreement_line l INNER JOIN adempiere.cms_agreement a ON " +
				"a.cms_agreement_id = l.cms_agreement_id WHERE a.CMS_Contract_ID = " + contract.get_ID();
		
		
		pstmt = DB.prepareStatement(sql, get_TrxName());
		rs = pstmt.executeQuery();
		
		try {
			while(rs.next()){
				X_cms_agreement_line line = new X_cms_agreement_line(getCtx(), rs.getInt("cms_agreement_line_ID"), get_TrxName());
				File outputFile = new File(fullPath.toString());
				MAttachment outputEntry = new MAttachment(m_ctx, line.get_Table_ID(), line.get_ID(), get_TrxName());
				if(outputEntry.getEntries() != null)
					outputEntry.deleteEntry(0);
				outputEntry.addEntry(outputFile);
				outputEntry.setTitle(title);
				outputEntry.setTextMsg(msg);
				outputEntry.saveEx();
			}
		}
		catch(Exception e){
			throw new Exception("Unable to create pattern");
		}

		
		
		/*File outputFile = new File(fullPath.toString());
		MAttachment outputEntry = new MAttachment(m_ctx, contract.get_Table_ID(), contract.get_ID(), get_TrxName());
		if(outputEntry.getEntries() != null)
			outputEntry.deleteEntry(0);
		outputEntry.addEntry(outputFile);
		outputEntry.setTitle(title);
		outputEntry.setTextMsg(msg);
		outputEntry.saveEx();
		*/
		SendMail();
		
		return true;
	}
	
	private boolean SendMail() throws Exception
	{
		int agreement_ID = 0;
		
		String sql2 = "SELECT max(cms_agreement_ID) from adempiere.cms_agreement where cms_contract_id = " + pattern.getCMS_Contract_ID();
		
		agreement_ID = DB.getSQLValue(get_TrxName(), sql2);
		
		if(agreement_ID == -1)
			return false;
		
		X_cms_agreement agreement = new X_cms_agreement(getCtx(),agreement_ID,get_TrxName());
		
		if(agreement.getAD_User_ID() == -1)
			throw new Exception("There is no value for AD_User_ID");
					
		X_R_MailText rText = new X_R_MailText(getCtx(), null, get_TrxName());
		
		X_CMS_Contract contract = new X_CMS_Contract(getCtx(),agreement.getCMS_Contract_ID(), get_TrxName());
		
		String message = "Вам необходимо рассмотреть и согласовать проект договора, номер карточки договора - " + contract.getDocumentNo();
		
		int C_BPartner_ID = agreement.getC_BPartner_ID();
		
		if(C_BPartner_ID == -1)
			throw new Exception("Unable to send message. C_BPartner is not filled");
		
		String userName = (new X_C_BPartner(getCtx(), C_BPartner_ID, get_TrxName())).getName();
		
		if(userName == "")
			userName = "Unknown";
		
		rText.setMailHeader("Согласование");
		rText.setMailText(message);
		rText.setName(userName);
		
		if(!rText.save())
			throw new Exception("Unnable to save mail pattern");
		
		MMailText mailText = new MMailText(getCtx(), rText.get_ID(), get_TrxName());						
		
		String sql = "SELECT AD_User_ID FROM adempiere.AD_User WHERE C_BPartner_ID = " + agreement.getC_BPartner_ID();
		
		int p_AD_User_ID = DB.getSQLValue(get_TrxName(), sql);		
		
		if(p_AD_User_ID < 0)
			throw new Exception("User_ID not found");
		
		int p_AD_Client_ID = Env.getAD_Client_ID(getCtx());
		
		MUser userFrom = new MUser(getCtx(), p_AD_User_ID, get_TrxName());
		MUser userTo = null;		
		MClient client = new MClient(getCtx(), p_AD_Client_ID, get_TrxName());		
		
		userTo = new MUser(getCtx(), agreement.getAD_User_ID(), get_TrxName());
		
		EMail mail = client.createEMail(userFrom, userTo, mailText.getMailHeader(), mailText.getMailText());		
		EMail.SENT_OK.equals(mail.send());		
		return true;
	}
}
